package com.wedo.mall.activity.user;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.e.library.activity.EActivity;
import com.e.library.http.EObserver;
import com.e.library.http.EResponse;
import com.e.library.widget.ETitleBar;
import com.hyphenate.easeui.EaseConstant;
import com.wedo.mall.R;
import com.wedo.mall.adapter.FragmentAdapter;
import com.wedo.mall.fragment.OrderAllFragment;
import com.wedo.mall.fragment.OrderNotreceivedFragment;
import com.wedo.mall.fragment.OrderPendingEvaluationFragment;
import com.wedo.mall.fragment.OrderUnpaidFragment;
import com.wedo.mall.fragment.OrderUnprocessedFragment;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observable;

public class MyOrderActivity extends EActivity {

    public static final String ORDER_SORT = "sort";
    public static final int SORT_ALL = 0;
    public static final int SORT_UNPAID = 1;
    public static final int SORT_UNPROCESSED = 2;
    public static final int SORT_NOTRECEIVED = 3;
    public static final int SORT_PENDINGEVALUATION = 4;
    private int sort = SORT_ALL;

    @BindView(R.id.title_bar) ETitleBar title_bar;
    @BindView(R.id.mTabLayout) TabLayout mTabLayout;

    //private String[] tabTitle = null;
    private List<String> titles = new ArrayList<>(5);
    private ArrayList<Fragment> fragments = new ArrayList<>(5);

    @BindView(R.id.mViewPager) ViewPager mViewPager;
    //private PagerAdapter pagerAdapter;

    @Override
    protected int layout() {
        return R.layout.activity_my_order;
    }

    @Override
    protected void onActivityCreated(Bundle state) {
        init();
    }

    private void init(){
        setTabLayout();


        //fragments = new ArrayList<>();
        fragments.add(OrderAllFragment.with());
        fragments.add(OrderUnpaidFragment.with());
        fragments.add(OrderUnprocessedFragment.with());
        fragments.add(OrderNotreceivedFragment.with());
        fragments.add(OrderPendingEvaluationFragment.with());

        titles.add(this.getString(R.string.user_all));
        titles.add(this.getString(R.string.user_unpaid));
        titles.add(this.getString(R.string.user_unprocessed));
        titles.add(this.getString(R.string.user_notreceived));
        titles.add(this.getString(R.string.user_pendingevaluation));

        FragmentAdapter adapter = new FragmentAdapter(this.getSupportFragmentManager(),fragments,titles);
        mViewPager.setOffscreenPageLimit(1);
        mViewPager.setAdapter(adapter);
        mTabLayout.setupWithViewPager(mViewPager,true);
        sort = getIntent().getIntExtra(ORDER_SORT,0);
        mViewPager.setCurrentItem(sort);

//        pagerAdapter = new MyOrderActivity.MyPagerAdapter(getSupportFragmentManager());
//        mViewPager.setAdapter(pagerAdapter);
//        //在设置viewpager页面滑动监听时，创建TabLayout的滑动监听
//        mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));
//
//        mTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
//            @Override
//            public void onTabSelected(TabLayout.Tab tab) {
//                //在选中的顶部标签时，为viewpager设置currentitem
//                mViewPager.setCurrentItem(tab.getPosition());
//            }
//
//            @Override
//            public void onTabUnselected(TabLayout.Tab tab) {
//
//            }
//
//            @Override
//            public void onTabReselected(TabLayout.Tab tab) {
//
//            }
//        });
//
//        sort = getIntent().getIntExtra(ORDER_SORT,0);
//        if(sort == SORT_ALL){
//            mTabLayout.getTabAt(0).select();
//            mViewPager.setCurrentItem(0);
//        }else if(sort == SORT_UNPAID){
//            mTabLayout.getTabAt(1).select();
//            mViewPager.setCurrentItem(1);
//        }else if(sort == SORT_UNPROCESSED){
//            mTabLayout.getTabAt(2).select();
//            mViewPager.setCurrentItem(2);
//        }else if(sort == SORT_NOTRECEIVED){
//            mTabLayout.getTabAt(3).select();
//            mViewPager.setCurrentItem(3);
//        }else if(sort == SORT_PENDINGEVALUATION){
//            mTabLayout.getTabAt(4).select();
//            mViewPager.setCurrentItem(4);
//        }

        title_bar.showForwardLayout();
        title_bar.setOnForwardListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestPhoneCall(tel);
            }
        });

        tel();
    }

    private void setTabLayout(){
//        tabTitle = new String[]{
//                this.getString(R.string.user_all),
//                this.getString(R.string.user_unpaid),
//                this.getString(R.string.user_unprocessed),
//                this.getString(R.string.user_notreceived),
//                this.getString(R.string.user_pendingevaluation)};
//        for (int i=0; i<tabTitle.length; i++) {
//            mTabLayout.addTab(mTabLayout.newTab().setText(tabTitle[i]));
//        }
//        mTabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
//        //设置顶部标签指示条的颜色和选中页面时标签字体颜色
//        mTabLayout.setSelectedTabIndicatorColor(getResources().getColor(R.color.e_purple));
//        mTabLayout.setTabTextColors(Color.GRAY,getResources().getColor(R.color.e_purple));
//
//        mTabLayout.post(new Runnable() {
//            @Override
//            public void run() {
//                setIndicator(mTabLayout, 15, 15);
//            }
//        });
    }

    //利用反射来修改tablayout的长度，最后在mTabLayout.post(new Runnable()中调用
    public void setIndicator (TabLayout tabs,int leftDip,int rightDip) {
//        Class<?> tabLayout = tabs.getClass();
//        Field tabStrip = null;
//        try {
//            tabStrip = tabLayout.getDeclaredField("mTabStrip");
//        } catch (NoSuchFieldException e) {
//            e.printStackTrace();
//        }
//
//        tabStrip.setAccessible(true);
//        LinearLayout llTab = null;
//        try {
//            llTab = (LinearLayout) tabStrip.get(tabs);
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        }
//
//        int left = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip, Resources.getSystem().getDisplayMetrics());
//        int right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip, Resources.getSystem().getDisplayMetrics());
//
//        for (int i = 0; i < llTab.getChildCount(); i++) {
//            View child = llTab.getChildAt(i);
//            child.setPadding(0, 0, 0, 0);
//            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
//            params.leftMargin = left;
//            params.rightMargin = right;
//            child.setLayoutParams(params);
//            child.invalidate();
//        }
    }

//    class MyPagerAdapter extends FragmentPagerAdapter {
//        public MyPagerAdapter(FragmentManager fm) {
//            super(fm);
//        }
//
//        @Override
//        public Fragment getItem(int position) {
//            return fragments.get(position);
//        }
//
//        @Override
//        public int getCount() {
//            return fragments.size();
//        }
//
//    }

    private String tel;
    private void tel(){
        Observable<EResponse> observable = api().tel(new HashMap<String, String>(1));
        observer(observable, new EObserver() {
            @Override
            public void successful(EResponse response) {
                tel = response.string("list");
            }

            @Override
            public void failure(String msg) {

            }
        });
    }

    public static final int REQ_PHONE_CALL = 104;
    public  void requestPhoneCall(String phone){
        if(TextUtils.isEmpty(phone)) {
            toast(R.string.consult_phone_invalid);
            return;
        }

        if(ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE},REQ_PHONE_CALL);
            return;
        }
        phoneCall(phone);
    }

    public void phoneCall(String phone){
        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+phone));
        startActivity(intent);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQ_PHONE_CALL){
            if (grantResults.length >0){
            }
        }
    }
}
